const express = require('express')
const router = express.Router()
const Address = require('../db/address')

// 获取用户地址列表
router.get('/list', async (req, res) => {
  try {
    const { userId = 'user123' } = req.query // 实际应该从token获取

    const addresses = await Address.find({ userId }).sort({ isDefault: -1, createTime: -1 })

    res.json({
      success: true,
      data: addresses,
      message: '获取地址列表成功'
    })

  } catch (error) {
    console.error('获取地址列表失败:', error)
    res.json({
      success: false,
      message: '获取地址列表失败'
    })
  }
})

// 创建新地址
router.post('/create', async (req, res) => {
  try {
    const { name, phone, fullAddress, isDefault, userId = 'user123' } = req.body

    // 验证必填字段
    if (!name || !phone || !fullAddress) {
      return res.json({
        success: false,
        message: '姓名、电话、地址为必填项'
      })
    }

    // 如果设置为默认地址，先将其他地址设为非默认
    if (isDefault) {
      await Address.updateMany(
        { userId },
        { isDefault: false }
      )
    }

    // 生成地址ID
    const id = Address.generateId()

    // 创建地址
    const address = new Address({
      id,
      name,
      phone,
      fullAddress,
      isDefault: isDefault || false,
      userId
    })

    // 保存地址
    await address.save()

    res.json({
      success: true,
      data: address,
      message: '地址创建成功'
    })

  } catch (error) {
    console.error('创建地址失败:', error)
    res.json({
      success: false,
      message: '创建地址失败'
    })
  }
})

// 更新地址
router.put('/update/:id', async (req, res) => {
  try {
    const { id } = req.params
    const { name, phone, fullAddress, isDefault, userId = 'user123' } = req.body

    // 验证必填字段
    if (!name || !phone || !fullAddress) {
      return res.json({
        success: false,
        message: '姓名、电话、地址为必填项'
      })
    }

    // 如果设置为默认地址，先将其他地址设为非默认
    if (isDefault) {
      await Address.updateMany(
        { userId },
        { isDefault: false }
      )
    }

    // 更新地址
    const address = await Address.findOneAndUpdate(
      { id, userId },
      {
        name,
        phone,
        fullAddress,
        isDefault: isDefault || false,
        updateTime: new Date()
      },
      { new: true }
    )

    if (!address) {
      return res.json({
        success: false,
        message: '地址不存在'
      })
    }

    res.json({
      success: true,
      data: address,
      message: '地址更新成功'
    })

  } catch (error) {
    console.error('更新地址失败:', error)
    res.json({
      success: false,
      message: '更新地址失败'
    })
  }
})

// 删除地址
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params
    const { userId = 'user123' } = req.query

    const address = await Address.findOneAndDelete({ id, userId })

    if (!address) {
      return res.json({
        success: false,
        message: '地址不存在'
      })
    }

    // 如果删除的是默认地址，将第一个地址设为默认
    if (address.isDefault) {
      const firstAddress = await Address.findOne({ userId }).sort({ createTime: 1 })
      if (firstAddress) {
        firstAddress.isDefault = true
        await firstAddress.save()
      }
    }

    res.json({
      success: true,
      message: '地址删除成功'
    })

  } catch (error) {
    console.error('删除地址失败:', error)
    res.json({
      success: false,
      message: '删除地址失败'
    })
  }
})

// 设置默认地址
router.put('/set-default/:id', async (req, res) => {
  try {
    const { id } = req.params
    const { userId = 'user123' } = req.body

    // 先将该用户的所有地址设为非默认
    await Address.updateMany(
      { userId },
      { isDefault: false }
    )

    // 将指定地址设为默认
    const address = await Address.findOneAndUpdate(
      { id, userId },
      { isDefault: true, updateTime: new Date() },
      { new: true }
    )

    if (!address) {
      return res.json({
        success: false,
        message: '地址不存在'
      })
    }

    res.json({
      success: true,
      data: address,
      message: '设置默认地址成功'
    })

  } catch (error) {
    console.error('设置默认地址失败:', error)
    res.json({
      success: false,
      message: '设置默认地址失败'
    })
  }
})

// 获取地址详情
router.get('/detail/:id', async (req, res) => {
  try {
    const { id } = req.params
    const { userId = 'user123' } = req.query

    const address = await Address.findOne({ id, userId })

    if (!address) {
      return res.json({
        success: false,
        message: '地址不存在'
      })
    }

    res.json({
      success: true,
      data: address,
      message: '获取地址详情成功'
    })

  } catch (error) {
    console.error('获取地址详情失败:', error)
    res.json({
      success: false,
      message: '获取地址详情失败'
    })
  }
})

module.exports = router

